<template>
  <div class="pagination">
    <button 
    :disabled="currentPage === 1"
    @click="$emit('changePage',currentPage - 1)"
    >上一页</button>

    <button 
    v-if="startEndPage.startPage > 1"
    :class="{ active: currentPage === 1 }"
    @click="$emit('changePage',1)"
    >1</button>

    <button
    v-if="startEndPage.startPage > 2"
    >···</button>

    <button
    :class="{ active: page === currentPage }"
    v-for="page in filterPages"
    :key="page"
    @click="$emit('changePage', page)"
  >
    {{ page }}
  </button>

    <button
    v-if="startEndPage.endPage < totalPage-1"
    >···</button>

    <button 
    v-if="startEndPage.endPage < totalPage"
    :class="{ active: currentPage === totalPage }"
    @click="$emit('changePage',totalPage)"
    >{{totalPage}}</button>

    <button 
    :disabled="currentPage === totalPage"
    @click="$emit('changePage',currentPage + 1)"
    >下一页</button>

    <button style="margin-left: 30px">共 {{total}} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props:["currentPage","totalPage","continuePage","total"],
  computed:{
      startEndPage(){
          let startPage,endPage;
          //先判断临界值如果连续页长度大于页码总长度:起始是1 结束是总长度
          if(this.continuePage > this.totalPage){
              startPage = 1;
              endPage = this.totalPage;
          }else{
              //如果连续页小于总页数,先计算出来连续页的开头和结尾
              startPage = this.currentPage - Math.floor(this.continuePage / 2);
              endPage = this.currentPage + Math.floor(this.continuePage / 2);

              //判断临界值,如果start<1 则start只能最小是1
              if(startPage < 1){
                  startPage = 1;
                  endPage = this.totalPage
              }
              //判断临界值,如果end>total,则end最大只能是total
              if(endPage > this.totalPage){
                  endPage = this.totalPage;
                  startPage = endPage - this.continuePage + 1;
              }
          }
          console.log(startPage, endPage);
    return {
      startPage,
      endPage,
    };
      },
      //因为v-if和v-for不能一起使用,所以我们可以根据条件,把v-for需要真正遍历出来的值一次放入数组中
  //未来在组件中直接遍历数组即可
  filterPages() {
    const arr = [];
    for (var i = 1; i <= this.startEndPage.endPage; i++) {
      if (i >= this.startEndPage.startPage) arr.push(i);
    }
    return arr;
  },
  }
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>

  